package com.hellacutty.shake;

import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.util.Log;

public class ShakeClass implements SensorListener, CanProvideShakes{
	private SensorManager sensorMgr;
	private long lastUpdate = -1;
	private float x, y, z;
	private float last_x, last_y, last_z;
	private static final int SHAKE_THRESHOLD = 600;
	private int shakeCount;
	public int getShakeCount(){
		return shakeCount;
	}
	public ShakeClass(SensorManager sm){
		sensorMgr = sm;
		boolean accelSupported = sensorMgr.registerListener(this,
				SensorManager.SENSOR_ACCELEROMETER,
				SensorManager.SENSOR_DELAY_GAME);

		if (!accelSupported) {
			// on accelerometer on this device
			sensorMgr.unregisterListener(this,
					SensorManager.SENSOR_ACCELEROMETER);
		}
	}
	@Override
	public void onAccuracyChanged(int sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(int sensor, float[] values) {
		if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
			long curTime = System.currentTimeMillis();
			// only allow one update every 100ms.
			if ((curTime - lastUpdate) > 50) {
				long diffTime = (curTime - lastUpdate);
				lastUpdate = curTime;

				x = values[SensorManager.DATA_X];
				y = values[SensorManager.DATA_Y];
				z = values[SensorManager.DATA_Z];

				float speed = Math.abs(x+y+z - last_x - last_y - last_z)
				/ diffTime * 10000;
				if (speed > SHAKE_THRESHOLD) {
					shakeCount+=10;
					Log.d("Shake", "Shake");
				}
				last_x = x;
				last_y = y;
				last_z = z;
			}
		}
	}
	public void disable(){
		sensorMgr.unregisterListener(this);
	}

}
